package top.infopub.mgr.mkt.service.impl;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.enums.mkt.ProProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.enums.sg.CoopInfoTypesEnums;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.WsFlowProcessService;
import top.infopub.mgr.mkt.dao.*;
import top.infopub.mgr.mkt.domain.CollectProjectDomain;
import top.infopub.mgr.mkt.domain.ProjectDomain;
import top.infopub.mgr.mkt.jsonvo.CollectJsonVo;
import top.infopub.mgr.mkt.service.BaseLineService;
import top.infopub.mgr.mkt.service.CollectProjectService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.mkt.vo.BaseLineVo;
import top.infopub.mgr.mkt.vo.CollectProjectVo;
import top.infopub.mgr.mkt.vo.InvestmentInfoVo;
import top.infopub.mgr.mkt.vo.ItemNameVo;
import top.infopub.mgr.sg.service.CoopInfoService;
import top.infopub.mgr.util.DateUtils;
import top.infopub.model.mkt.*;
import top.infopub.model.sg.CoopInfo;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class CollectProjectServiceImpl extends GenericServiceImpl<CollectProject, String> implements CollectProjectService {

    @Autowired
    private CollectProjectDao collectProjectDao;

    @Autowired
    private CollectProjectCoopDao collectProjectCoopDao;

    @Autowired
    private CollectProjectSubDao collectProjectSubDao;

    @Autowired
    private CollectProjectAttDao collectProjectAttDao;

    @Autowired
    private PreProjectDao preProjectDao;

    @Autowired
    private PreProjectCoopDao preProjectCoopDao;

    @Autowired
    private PreProjectSubDao preProjectSubDao;

    @Autowired
    private PreProjectAttDao preProjectAttDao;

    @Autowired
    private WsFlowProcessService wsFlowProcess;

    @Autowired
    private BaseLineService baseLineService;

    @Autowired
    private ProjectInfoDao projectInfoDao;
    @Autowired
    private AfterSummaryCoopDao afterSummaryCoopDao;

    @Autowired
    private ProjectSubInfoDao projectSubInfoDao;
    @Autowired
    private ProjectRiskDao projectRiskDao;
    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;
    @Autowired
    private CoopInfoService coopInfoService;
    @Autowired
    private ProProcessManageService proProcessManageService;

    @Autowired
    private ProTrackDao proTrackDao;

    @Override
    public GenericDao<CollectProject, String> getDao() {
        return collectProjectDao;
    }

    @Override
    public Page<ProjectDomain> selectPageByDomainWhere(Page<ProjectDomain> page,
                                                       CollectProjectVo collectProjectVo) {
        //处理时间范围
        if (!StringUtils.isEmpty(collectProjectVo.getDates())) {
            String[] splitTime = collectProjectVo.getDates().split("~");
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            try {
                collectProjectVo.setEndDate(format.parse(splitTime[1]));
                collectProjectVo.setStartDate(format.parse(splitTime[0]));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<ProjectDomain>)collectProjectDao.selectByDomainWhere(collectProjectVo);
    }

    /*@Override
    public Page<CollectProjectDomain> selectMyCheckByDomainWhere(Page<CollectProjectDomain> page,
                                                                 CollectProjectVo collectProjectVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<CollectProjectDomain>)collectProjectDao.selectMyCheckByDomainWhere(collectProjectVo);
    }*/

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addCollectProject(CollectProject collectProject, List<CollectProjectCoop> collectProjectCoops, List<CollectProjectSub> collectProjectSubs, List<CollectProjectAtt> fileAtts) {
        //插入信息收集记录
        collectProjectDao.insertById(collectProject);

        //批量插入联合体单位
        if (CollectionUtils.isNotEmpty(collectProjectCoops)) {
            collectProjectCoopDao.insertByBatch(collectProjectCoops);
        }

        //批量插入子项
        if (CollectionUtils.isNotEmpty(collectProjectSubs)) {
            collectProjectSubDao.insertByBatch(collectProjectSubs);
        }

        //批量插入附件
        if (CollectionUtils.isNotEmpty(fileAtts)) {
            collectProjectAttDao.insertByBatch(fileAtts);
        }

       /* // 注意 这里根据不同的业务分支判断条件 获得不同enum
        FlowTemplateEnum templateEnum = FlowTemplateEnum.MKT_PRE_PROJECT;
        // 处理工作流数据
        wsFlowProcess.launch(templateEnum, preProject.getId(), preProject.getProcessId());*/

    }

    @Override
    @Transactional
    public void editCollectProject(CollectProject collectProject, List<CollectProjectCoop> collectProjectCoops, List<CollectProjectSub> collectProjectSubs, List<CollectProjectAtt> fileAtts,String submitType) {
        collectProjectDao.updateByIdSelective(collectProject);
        collectProjectSubDao.deleteByProjectId(collectProject.getId());
        collectProjectCoopDao.deleteByProjectId(collectProject.getId());
        collectProjectAttDao.deleteByProjectId(collectProject.getId());

        //批量插入联合体单位
        if (CollectionUtils.isNotEmpty(collectProjectCoops)) {
            collectProjectCoopDao.insertByBatch(collectProjectCoops);
        }

        //批量插入子项
        if (CollectionUtils.isNotEmpty(collectProjectSubs)) {
            collectProjectSubDao.insertByBatch(collectProjectSubs);
        }

        //批量插入附件
        if (CollectionUtils.isNotEmpty(fileAtts)) {
            collectProjectAttDao.insertByBatch(fileAtts);
        }

        if("2".equalsIgnoreCase(submitType)){//2=提交  1保存
            //判断是否满足预立项条件
//            String sgCityId = collectProject.getSgCityId();
            CollectProjectVo collectProjectVo = collectProjectDao.selectById(collectProject.getId());
//            List<BaseLineVo> baseLines = baseLineService.selectBySgCityId(sgCityId,1,collectProjectVo);
//            for (BaseLineVo baseLine : baseLines) {
//                if(!baseLine.getResult()){
//                    return;
//                }
//            }

            //处理预立项信息
            CollectProject collect=new CollectProject();
            collect.setId(collectProject.getId());
//            collect.setStep("2");
            collectProjectDao.updateByIdSelective(collect);
            collect=collectProjectDao.selectById(collect.getId());
            PreProject preProject=new PreProject();
            List<PreProjectCoop> preProjectCoops=new ArrayList<>();
            List<PreProjectSub> preProjectSubs=new ArrayList<>();
            List<PreProjectAtt> preProjectAtts=new ArrayList<>();
            BeanUtils.copyProperties(collect,preProject);
            // 处理processId
            preProject.setProcessId(IdFactory.getUUIDUpper());
            preProject.setProcessStatus("0");
            preProjectDao.insertById(preProject);
            if (CollectionUtils.isNotEmpty(collectProjectCoops)) {
                for (CollectProjectCoop collectProjectCoop : collectProjectCoops) {
                    PreProjectCoop coop=new PreProjectCoop();
                    BeanUtils.copyProperties(collectProjectCoop,coop);
                    preProjectCoops.add(coop);
                }
                preProjectCoopDao.insertByBatch(preProjectCoops);
            }
            if (CollectionUtils.isNotEmpty(collectProjectSubs)) {
                for (CollectProjectSub collectProjectSub : collectProjectSubs) {
                    PreProjectSub sub=new PreProjectSub();
                    BeanUtils.copyProperties(collectProjectSub,sub);
                    preProjectSubs.add(sub);
                }
                preProjectSubDao.insertByBatch(preProjectSubs);
            }
            if (CollectionUtils.isNotEmpty(fileAtts)) {
                for (CollectProjectAtt fileAtt : fileAtts) {
                    PreProjectAtt att=new PreProjectAtt();
                    BeanUtils.copyProperties(fileAtt,att);
                    preProjectAtts.add(att);
                }
                preProjectAttDao.insertByBatch(preProjectAtts);
            }
        }




    }

    @Override
    public CollectProjectVo selectById(String id) {
        return collectProjectDao.selectById(id);
    }


    @Override
    public CollectProjectDomain queryByProCode(String proCodes) {
        return collectProjectDao.queryByProCode(proCodes);
    }


    @Override
    public List<CollectProject> selectNotBindOrg() {
        return collectProjectDao.selectNotBindOrg();
    }

    @Override
    public List<CollectProject> selectByProName(String proName) {
        return collectProjectDao.selectByProName(proName);
    }

    @Override
    public CollectProject selectByProCode(String proCode) {
        return collectProjectDao.selectByProCode(proCode);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RspVo saveAll(ProjectInfo projectInfo, List<AfterSummaryCoop> summary, ProjectSubInfo projectSubInfo, List<ProjectRisk> projectRisk, List<ProjectAttachment> attachmentList, CollectProject collectProject, AuthorizationVO user, String bodyStr, Integer submitType) {

        //查询项目审核状态
//        CollectProject collect = collectProjectDao.selectByProCodeStatus(projectInfo.getProCode());
        PreProject preProject1 = preProjectDao.selectByProCode(projectInfo.getProCode());
        ProTrack proTrack2 = proTrackDao.selectByProCode(projectInfo.getProCode());
        //判断审批状态
        if (preProject1!=null && submitType==2 && "1".equals(preProject1.getProcessStatus())) {
                return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
        }
        if (proTrack2!=null && StringUtils.isNotBlank(proTrack2.getProcessStatus())&&submitType==1) {
            if(StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), proTrack2.getProcessStatus())){
                return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
            }
        }
        //更新项目基础信息
        ProjectInfo byProCode = projectInfoDao.findTailByProCode(projectInfo.getProCode());
        if (byProCode!=null){
            projectInfo.setId(byProCode.getId());
            projectInfo.setUptBy(user.getId());
            projectInfo.setUptTime(new Date());
            //更新项目基础信息
            projectInfoDao.modifyProjectInfoBySeletive(projectInfo);
            CollectProject collectProject2 = collectProjectDao.selectByProCodeStatus(byProCode.getProCode());
            collectProject2.setUptBy(user.getId());
            collectProject2.setUptTime(new Date());
            collectProject2.setProCode(projectInfo.getProCode());
            collectProjectDao.updateById(collectProject2);
        }else{
            //更新项目基础信息
            projectInfoDao.insert(projectInfo);
            //更新项目信息收集
            collectProjectDao.insert(collectProject);
        }

        //更新项目合作单位信息
        afterSummaryCoopDao.deleteByProCode(projectInfo.getProCode());
        AfterSummaryCoop aft = new AfterSummaryCoop();
        aft.setSgCoopId(projectInfo.getUnitId());
//        aft.setSgCoopId("1");
        aft.setCoopEffect("-1");
        aft.setCooperationType("-1");
        summary.add(aft);
        for (AfterSummaryCoop summaryCoop : summary) {
            summaryCoop.setId(IdFactory.getUUIDUpper());
            summaryCoop.setProCode(projectInfo.getProCode());
            summaryCoop.setAddBy(user.getId());
            summaryCoop.setAddTime(DateUtils.getCurrentDateTime());
        }
        afterSummaryCoopDao.insertByBatch(summary);

        //更新项目投资构成信息
        ProjectSubInfo psi = projectSubInfoDao.queryByProCode(projectInfo.getProCode());
        if (psi!=null){
            projectSubInfoDao.deleteByPrimaryKey(psi.getId());
        }
        projectSubInfo.setProCode(projectInfo.getProCode());
        projectSubInfoDao.insert(projectSubInfo);
        //获取当前阶段
        String node = proProcessManageService.queryProProcessType(projectInfo.getProCode()).getNode();
        //更新风险信息
        if (projectRisk.size()>0){
            projectRiskDao.deleteByProCode(projectInfo.getProCode());
            for (ProjectRisk risk : projectRisk) {
                risk.setId(IdFactory.getUUIDUpper());
                risk.setProCode(projectInfo.getProCode());
                risk.setStatus("0");
                risk.setAddBy(user.getId());
                risk.setRiskStage(node);
                risk.setAddTime(new Date());
                risk.setRiskDesc(risk.getRiskDesc() != null ? risk.getRiskDesc() : "");
                risk.setRiskLevel(risk.getRiskLevel() != null ? risk.getRiskLevel() : "");
                risk.setSolveWay(risk.getSolveWay() != null ? risk.getSolveWay() : "");
                risk.setLatestProgress(risk.getLatestProgress() != null ? risk.getLatestProgress() : "");
                risk.setUpdateBy(risk.getId());
                risk.setUpdateTime(new Date());
                risk.setAddTime(DateUtils.getCurrentDateTime());
            }
            projectRiskDao.insertBatch(projectRisk);
        }

        if (attachmentList!=null && attachmentList.size()>0){
            //批量插入附件信息
            projectAttachmentDao.deleteByWhere(projectInfo.getProCode(), ProjectFileTypeEnum.FILE_TYPE2.getCode(), null);
            for (ProjectAttachment attachment : attachmentList) {
                attachment.setProCode(projectInfo.getProCode());
            }
            projectAttachmentDao.insertBatch(attachmentList);
        }
        //保存
        //提交发起跟踪流程
//        CollectProject collectProject1 = collectProjectDao.selectByProCodeStatus(projectInfo.getProCode());
        //查询跟踪信息是否存在
        if (submitType ==1){
        ProTrack proTrack1 = proTrackDao.selectByProCode(projectInfo.getProCode());
        if (proTrack1==null){
            ProTrack proTrack = new ProTrack();
            proTrack.setId(IdFactory.getUUIDUpper());
            proTrack.setTrackStatus("0");
            proTrack.setProCode(projectInfo.getProCode());
            proTrack.setAddBy(user.getId());
            proTrack.setAddTime(new Date());
            proTrack.setTodayMemo(null);
            proTrack.setTomorrowPlan(null);
            proTrack.setProcessId("1");
            proTrack.setProcessStatus("1");
             proTrackDao.insert(proTrack);
            proProcessManageService.sendProcess(ProProcessDetailTypeEnum.PRO_NODE_TYPE18, bodyStr, proTrack.getId(), projectInfo.getProCode(), user);
        }else{
            proProcessManageService.sendProcess(ProProcessDetailTypeEnum.PRO_NODE_TYPE18, bodyStr, proTrack1.getId(), projectInfo.getProCode(), user);
        }
 }
        //提交  直接发起预立项流程  submit =2
        if(submitType == 2){
            PreProject preProject = new PreProject();
            preProject.setId(IdFactory.getUUIDUpper());
            preProject.setAddBy(user.getId());
            preProject.setAddTime(new Date());
            preProject.setProCode(projectInfo.getProCode());
            preProject.setCodes(IdFactory.getUUIDUpper());
            preProject.setProcessStatus("1");
            preProject.setIsMeet("0");  //默认为满足
            List<BaseLineVo> baseLineVos = baseLineService.checkIsSatisfy(projectInfo.getProCode());
            for (BaseLineVo baseLineVo : baseLineVos) {
                if (!baseLineVo.getResult()){
                    preProject.setIsMeet("1");
                    break;
                }
            }
            ProTrack proTrack3 = proTrackDao.selectByProCode(projectInfo.getProCode());
            if (proTrack3==null){//无跟踪流程  添加跟踪信息
                ProTrack proTrack4 = new ProTrack();
                proTrack4.setId(IdFactory.getUUIDUpper());
                proTrack4.setTrackStatus("0");
                proTrack4.setProCode(projectInfo.getProCode());
                proTrack4.setAddBy(user.getId());
                proTrack4.setAddTime(new Date());
                proTrack4.setTodayMemo(null);
                proTrack4.setTomorrowPlan(null);
                proTrack4.setProcessId("1");
                proTrack4.setProcessStatus("9");
                proTrackDao.insert(proTrack4);
            }
            preProjectDao.insertById(preProject);
            String s = proProcessManageService.sendProcess(ProProcessDetailTypeEnum.PRO_NODE_TYPE1, bodyStr, preProject.getId(), projectInfo.getProCode(), user);
            return RspVo.getSuccessResponse(s);
        }
        return RspVo.getSuccessResponse();
    }

    @Override
    public CollectJsonVo queryDetailById(String id) {
        CollectJsonVo collectJsonVo = new CollectJsonVo();
        //基础信息
        CollectProject collectProject = collectProjectDao.selectByPrimaryKey(id);
        String proCode = collectProject.getProCode();
        ProjectInfo projectInfo = projectInfoDao.findTailByProCode(proCode);
        projectInfo.setProcessId(collectProject.getProcessId());
        projectInfo.setPreId(collectProject.getId());
        collectJsonVo.setProjectInfo(projectInfo);
         //项目合作单位信息
        collectJsonVo.setSummaryCoops(afterSummaryCoopDao.querySummaryCoopList(projectInfo.getProCode(), 0));
        //项目投资构成信息
        ProjectSubInfo projectSubInfo = projectSubInfoDao.queryByProCode(projectInfo.getProCode());
        if (projectSubInfo != null) {
            if (StringUtils.isNotBlank(projectSubInfo.getTitleJson())) {
                collectJsonVo.setItemName(JSON.parseArray(projectSubInfo.getTitleJson(), ItemNameVo.class));
            }
            if (StringUtils.isNotBlank(projectSubInfo.getContentJson())) {
                collectJsonVo.setInvestmentInfoVos(JSON.parseArray(projectSubInfo.getContentJson(), InvestmentInfoVo.class));
            }
        }

        //项目风险信息
        collectJsonVo.setRiskTable(projectRiskDao.selectByProCode(projectInfo.getProCode()));
        //底线标准情况
        collectJsonVo.setStandardTable(baseLineService.checkIsSatisfy(projectInfo.getProCode()));
        //附件信息表
        List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(projectInfo.getProCode(), ProjectFileTypeEnum.FILE_TYPE2.getCode(), null);
        collectJsonVo.setFileAtt(fileAttaListToArray(projectAttaList));
        //合作单位信息
        List<CoopInfo> coopInfoList = coopInfoService.queryByTypes(CoopInfoTypesEnums.OWNER, 1);
        collectJsonVo.setCoopInfoList(coopInfoList);

        return collectJsonVo;
    }

    @Override
    public CollectProject selectByProCodeStatus(String proCode) {

        return collectProjectDao.selectByProCodeStatus(proCode);
    }


    public String[] fileAttaListToArray(List<ProjectAttachment> list) {
        if (list == null || list.size() <= 0) return null;
        String[] attaArr = new String[list.size()];
        int index = 0;
        for (ProjectAttachment pa : list) {
            StringBuffer tmp = new StringBuffer();
            tmp.append(pa.getSubTypes());
            tmp.append("|");
            tmp.append(pa.getFileName());
            tmp.append(pa.getFileSuffix());
            tmp.append("|");
            tmp.append(IdFactory.getUUIDSerialNumber());
            tmp.append("|");
            tmp.append(pa.getFilePath());
            attaArr[index] = tmp.toString();
            index++;
        }
        return attaArr;
    }

}
